package e.odbo.data.loader;

import com.openbravo.data.basic.BasicException;
import com.openbravo.data.loader.I_Session;
import com.openbravo.data.loader.dialect.SessionDialect;

import java.sql.Connection;
import java.util.Random;

public class SlaveSession implements I_Session {
    I_Session master;
    I_Session[] slaves;

    public SlaveSession(I_Session master, I_Session ...slaves) {
        this.master = master;
        this.slaves = slaves;
    }


    @Override
    public void connect() throws BasicException {
        master.connect();
    }

    @Override
    public void close() {
        master.close();
        for(I_Session session:slaves)
            session.close();
    }

    @Override
    public Connection getConnection() throws BasicException {
        return master.getConnection();
    }

    @Override
    public Connection getConnection(boolean readOnly) throws BasicException {
        if(!readOnly)
            return getConnection();
        I_Session session;
        if(slaves.length==1)
            session=slaves[0];
        else
            session=slaves[new Random(slaves.length).nextInt(slaves.length)];
        return session.getConnection();
    }

    @Override
    public void begin() throws BasicException {
        master.begin();
    }

    @Override
    public void commit() throws BasicException {
        master.commit();
    }

    @Override
    public void rollback() throws BasicException {
        master.rollback();
    }

    @Override
    public boolean isTransaction() {
        return master.isTransaction();
    }

    @Override
    public String getURL() throws BasicException {
        return master.getURL();
    }

    @Override
    public SessionDialect getDialect() {
        return master.getDialect();
    }

    @Override
    public String getPlatform() {
        return master.getPlatform();
    }
}
